import datetime
import os
from os.path import join
import pprint
import re
import time
import xlwt
import pandas as pd
import csv
import itertools

import filter_


def month_report(m, path='/Users/ww/Music/aiml/curated/movies'):
    st = time.time()
    folders = os.listdir(path)
    result = dict()
    result_ = dict()
    result__ = dict()
    for folder in folders:
        p = join(path, folder) # 拼接路径 /Users/ww/Music/aiml/curated/movies/...
        if os.path.isdir(p) and folder.startswith('2'):

            year, month, day = folder[:4], folder[4:6], folder[6:8]
            if month == str(m):
                for file in os.listdir(p):
                    if file.endswith('.mp4'):
                        info = re.match('(.*_\d{8})_(\w+)000.*', file)
                        name_in_list = info.group(1).replace('session00', 'session') + '.mov'
                        vc = info.group(2)
                        use_case = filter_.uc_value(name_in_list)
                        if use_case in result:
                            result[use_case][vc.lower()] += 1
                        else:
                            result[use_case] = {'xiaobu': 0, 'xiaoai': 0, 'xiaoyi': 0, 'breeno': 0, 'jovi': 0}
                            result[use_case][vc.lower()] += 1
                        if use_case not in result_:
                            result_[use_case] = {'xiaobu': 0, 'xiaoai': 0, 'xiaoyi': 0, 'breeno': 0, 'jovi': 0}
                            result_[use_case][vc.lower()] = 1
                        elif result_[use_case][vc.lower()] == 0:
                            result_[use_case][vc.lower()] = 1
                for k, v in result_.items():
                    if k in result__:
                        for i in v:
                            if result_[k][i] > 0:
                                result__[k][i] += 1
                    else:
                        result__[k] = v
                result_ = dict()

    print((time.time() - st) / 60, 'min')
    return result, result__


def week_report(path='/Users/ww/Music/aiml/curated/movies'):
    st = time.time()
    folders = os.listdir(path)
    result = dict()
    result_ = dict()
    result__ = dict()

    std = datetime.date(*map(int, input('eg:2020/8/8\ndate: ').split('/')))
    one_day = datetime.timedelta(days=1)
    days = []
    for i in range(7):
        days.append(str(std + one_day))
        std += one_day

    for folder in folders:
        p = join(path, folder)
        if os.path.isdir(p) and folder.startswith('2'):
            year, month, day = folder[:4], folder[4:6], folder[6:8]
            if '-'.join([year, month, day]) in days:
                for file in os.listdir(p):
                    if file.endswith('.mp4'):
                        info = re.match('(.*_\d{8})_(\w+)000.*', file)
                        name_in_list = info.group(1).replace('session00', 'session') + '.mov'
                        vc = info.group(2)
                        use_case = filter_.uc_value(name_in_list)


                        if use_case is None:
                            print(name_in_list)


                        if use_case in result:
                            result[use_case][vc.lower()] += 1
                        else:
                            result[use_case] = {'xiaobu': 0, 'xiaoai': 0, 'xiaoyi': 0, 'breeno': 0, 'jovi': 0}
                            result[use_case][vc.lower()] += 1
                        if use_case not in result_:
                            result_[use_case] = {'xiaobu': 0, 'xiaoai': 0, 'xiaoyi': 0, 'breeno': 0, 'jovi': 0}
                            result_[use_case][vc.lower()] = 1
                        elif result_[use_case][vc.lower()] == 0:
                            result_[use_case][vc.lower()] = 1
                for k, v in result_.items():
                    if k in result__:
                        for i in v:
                            if result_[k][i] > 0:
                                result__[k][i] += 1
                    else:
                        result__[k] = v
                result_ = dict()

    print((time.time() - st) / 60, 'min')
    return result, result__


def merge_dict(d1, d2):
    for k, v in d2.items():
        if k in d1:
            for i in v:
                d1[k][i] += d2[k][i]
        else:
            d1[k] = d2[k]
    return d1


def export_excel(data, name):
    export = [data]
    final_df = pd.DataFrame()
    for id in range(0, len(export)):
        df = pd.DataFrame.from_dict(export[id])
        final_df = pd.concat([final_df, df], axis=1)
        final_df = pd.DataFrame(final_df.values.T, index=final_df.columns, columns=final_df.index)
    print(final_df)
    file_path = pd.ExcelWriter('%s.xlsx' % name)
    final_df.to_excel(file_path, encoding='utf-8', index=True)
    file_path.save()


def report_old(duration=7, path='/Users/ww/Music/aiml/curated/movies', simple=True):
    st = datetime.date(*map(int, input('eg:2020/8/8\ndate: ').split('/')))
    one_day = datetime.timedelta(days=1)
    folders = os.listdir(path)
    result = dict()

    the_day = st

    for i in range(duration):
        result[str(the_day)] = {'amount': 0, 'par': 0, 'size/GB': 0}
        the_day += one_day

    for folder in folders:
        p = join(path, folder)
        if os.path.isdir(p) and folder.startswith('2'):
            year, month, day = folder[:4], folder[4:6], folder[6:8]
            d = '-'.join([year, month, day])
            par = 0
            if d in result:
                par += 1
                size = 0
                amount = 0
                for file in os.listdir(p):
                    if file.endswith('.mp4'):
                        size += os.path.getsize(join(p, file)) / (1024 ** 3)
                        amount += 1

                result[d]['amount'] += amount
                result[d]['par'] += par
                result[d]['size/GB'] += size

    pprint.pprint(result)
    week_result = {'week': '   -   '.join([str(st), str(st + ((duration - 1) * one_day))]), 'trials': 0, 'participant': 0}
    if simple:
        for k, v in result.items():
            week_result['trials'] += v['amount']
            week_result['participant'] += v['par']
        return week_result
    return result


# export_excel(a,'Trials - Use Case --3')
# export_excel(b,'Participant - Use Case --3')


# f = [a,b,c,d,e]
# g = {'trials':0,'participant':0}
#
# for i in f:
#     g['trials'] += i['trials']
#     g['participant'] += i['participant']





